package com.tbit.uqbike.client.util;

import com.alibaba.fastjson.JSONObject;
import com.tbit.uqbike.client.exception.BaseException;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Provider;
import java.security.Security;
import java.util.Arrays;

/**
 * 微信小程序工具类
 *
 * @author Leon
 * 2019年9月10日 下午5:18:15
 */
public class WxMPUtil {

    /**
     * 小程序解密用户数据
     *
     * @param encryptedData
     * @param code
     * @param iv
     * @return
     */
    public static String decryptionUserPhone(String appId, String secret, String code, String encryptedData, String iv, StringBuffer stringBuffer) {
        /**获取sessionKey*/
        String sessionKey = MyX509TrustManager.getSessionKey(code, appId, secret, stringBuffer);
        if (sessionKey == null) {
            throw new BaseException("-1005", "微信授权登录失败");
        }

        byte[] dataByte = Base64.decodeBase64(encryptedData);
        byte[] keyByte = Base64.decodeBase64(sessionKey);
        byte[] ivByte = Base64.decodeBase64(iv);

        try {
            // 如果密钥不足16位，那么就补足. 这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            Provider provider = Security.getProvider(BouncyCastleProvider.PROVIDER_NAME);
            if (provider == null) {
                provider = new BouncyCastleProvider();
                Security.addProvider(provider);
            }
            // 初始化
            //Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                JSONObject object = JSONObject.parseObject(result);

                return object.getString("phoneNumber");
            }
        } catch (Exception e) {
            LogUtil.warn("获取微信用户手机号码异常：" + e.getMessage());
        }

        return null;
    }


}
